﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Singer.Middleware.EFCore;

/// <summary>
/// EFCore 服务拓展
/// </summary>
public static class EFCoreServiceExtensions
{
    public static void AddEFCore<TDbContext>(this IServiceCollection services, IConfiguration configuration)
        where TDbContext : EFCoreDbContext
    {
        EFCoreOptions? options = configuration.GetSection(EFCoreOptions.ConfigKey).Get<EFCoreOptions>();
        if (options == null)
            throw new Exception("【EFCore】Config was not found.");
        options.Validate();
        services.Configure<EFCoreOptions>(configuration.GetSection(EFCoreOptions.ConfigKey));
        Action <DbContextOptionsBuilder> builderAcion = null;
        switch (options.DataType)
        {
            case DatabaseType.SqlServer:
                builderAcion = opt => opt.UseSqlServer(options.ConnectionString);
                break;
            default:
                throw new Exception($"【EFCore】This DataType '{options.DataType}' was not supported.");
        }
        services.AddDbContext<TDbContext>(builderAcion);
    }
}
